#pragma once
#include <iostream>
#include <string>
#include <set>

#include "InterAddr.hpp"
#include "Log.hpp"

using namespace LogModule;

/* 只允许执行白名单的命令 */
class Command
{
public:
    Command()
    {
        // 严格匹配
        _white_list.insert("ls");
        _white_list.insert("pwd");
        _white_list.insert("ls -l");
        _white_list.insert("touch haha.txt");
        _white_list.insert("who");
        _white_list.insert("whoami");
    }

    bool IsExistCommand(const std::string &cmd)
    {
        auto it = _white_list.find(cmd);
        return it != _white_list.end();
    }

    std::string Execute(const std::string cmd, InterAddr &addr)
    {
        if(!IsExistCommand(cmd))
        {
            return std::string("Bad Cmd! Can not Execute!");
        }

        FILE* fp = popen(cmd.c_str(), "r");
        if(nullptr == fp)
        {
            return std::string("Your cmd is not exist!");
        }

        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line;
        }

        pclose(fp);
        std::string result = addr.AddrName() + "Execute done, result is: \n" + res;
        LOG(LogLevel::DEBUG) << result;
        return result;
    }

    ~Command()
    {
        
    }
private:
    std::set<std::string> _white_list;
};